#include <time.h>
#include <stdlib.h>
#include <unordered_map>
#include <utility>

#include "../source/EventLoop.hpp"
#include "../source/Socket.hpp"
#include "../source/Connect.hpp"
#include "../source/Server.hpp"

std::unordered_map<uint32_t, PtrConnection> _conns; //<connId,连接ptr>
uint64_t connId = 0;                                // 连接id
EventLoop loop;

// 连接断开
void ConnectionDestory(const PtrConnection &conn)
{
    DLOG("connect destory");
    _conns.erase(conn->Id());
}

// 收到客户端消息回调
void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DLOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());

    // 回复客户端
    std::string str = "你好xx用户,我已收到你的消息,此消息为回复";
    conn->Send(str.c_str(), str.size());

}

// 有新客户端连接
void OnConnected(const PtrConnection &conn)
{
    DLOG("new connect:%d,%p", conn->Fd(), conn.get());
}

void Accept(EventLoop *loop, Channel *lst_channel)
{
    int fd = lst_channel->GetFd();
    int newfd = accept(fd, nullptr, nullptr); // 新连接获取
    if (newfd < 0)
    {
        return;
    }

    PtrConnection conn(new Connection(loop, connId, newfd)); // 为新连接创建连接管理
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetClosedCallback(std::bind(ConnectionDestory, std::placeholders::_1));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));

    conn->EnableInactiveRelease(10); // 10s销毁
    conn->Established();

    _conns.insert(std::make_pair(connId, conn));
    connId++;
}

void NewConnection(int newfd)
{
    
    PtrConnection conn(new Connection(&loop, connId, newfd)); // 为新连接创建连接管理
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetClosedCallback(std::bind(ConnectionDestory, std::placeholders::_1));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));

    conn->EnableInactiveRelease(10); // 10s销毁
    conn->Established();

    _conns.insert(std::make_pair(connId, conn));
    connId++;
}
int main()
{

    // srand(time(nullptr));

    // EventLoop loop;
    // Socket lst_sock;
    // lst_sock.CreateServer(8500);

    // Channel lst_channel(&loop, lst_sock.Fd());
    // lst_channel.SetReadCallback(std::bind(Acceptor,&loop, &lst_channel));
    // lst_channel.EnableRead();//启动监听套接字读监控

    Acceptor acc(&loop,8500);
    acc.SetAcceptCallback(std::bind(NewConnection,std::placeholders::_1));
    acc.Listen();
    
    while (1)
    {
        loop.Start();
    }

    
    return 0;
}